package jsyf.oa.service.report;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.report.ReportTemplateDao;
import jsyf.oa.entity.report.TemplateEntity;
import jsyf.oa.facade.report.ReportTemplateFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2017/12/11.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ReportTemplateService implements ReportTemplateFacade {
    @Autowired
    private ReportTemplateDao dao;

    @Override
    public String save(String jsonData) {
        TemplateEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), TemplateEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            dao.update(entity);
        }
        return entity.getId();
    }

    @Override
    public Boolean removeById(String id) {
        return dao.removeById(id) > 0;
    }

    @Override
    public List<JSONObject> getTreeNodes() {
        List<JSONObject> nodeList = new ArrayList<>();

        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id", "0");
        nodeRoot.put("pId", "-1");
        nodeRoot.put("name", "报表模板");
        nodeRoot.put("type", "root");
        nodeRoot.put("isParent", true);
        nodeRoot.put("open", true);
        nodeList.add(nodeRoot);

        List<JSONObject> list = dao.getJSONListByCondition("", new Object[]{});
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            node.put("pId", "0");
            node.put("type", "template");
            nodeList.add(node);
        }

        return nodeList;
    }
}
